<?php
/**
 * User:chendenan
 * Created On 2022/3/6 06 19:33
 */
namespace app\admin\controller;

use app\admin\controller\AdminBase;
use think\facade\View;

class Login extends AdminBase{
    public function initialize(){
        if($this->isLogin()){
            return $this->redirect(url("index/index"));
        }
    }

    public function index(){
        return View::fetch();
    }
    public function check(){
        if(!$this->request->isPost()){
            return show('请求方式错误',config('status.error'));
        }
        //参数校验
        // 从 原生方式验证
        $username = $this->request->param('username','','trim');
        $password = $this->request->param('password','','trim');
        $captcha = $this->request->param('captcha','','trim');
        //原生验证 取消 改为验证器验证
//        if( empty($username) || empty($password) || empty($captcha) ){
//            return show('参数不能为空',config('status.error'));
//        }
        $data = [
            'username' => $username,
            'password' => $password,
            'captcha'  => $captcha,
        ];
        $validate = new \app\admin\validate\AdminUser();
        if(!$validate->check($data)){
            return show($validate->getError(),config('status.error'));
        }
        // 需要校验验证码 改为验证器验证
//        if(!captcha_check($captcha)){
//            // 验证码校验失败
//            return show('验证码不正确'.$captcha,config('status.error'));
//        }
        try {
            $adminUserBus = new \app\admin\business\AdminUser();
            $result = $adminUserBus->login($data);
        } catch (\Exception $e){
            // 记录日志 $e->getMessage()
            return show($e->getMessage(),config('status.error'));
        }
        if($result){
            return show('登录成功',config('status.success'));
        }
        return show($validate->getError(),config('status.error'));
    }
}